import axios from 'axios';
import qs from 'qs';
import { baseURL } from '@/config/host';

// 判断是否是纯对象
const isPlainObject = function isPlainObject(obj) {
  let proto, Ctor;
  if (!obj || Object.prototype.toString.call(obj) !== '[object Object]')
    return false;
  proto = Object.getPrototypeOf(obj);
  if (!proto) return true;
  Ctor = proto.hasOwnProperty('constructor') && proto.constructor;
  return typeof Ctor === 'function' && Ctor === Object;
};

// create an axios instance
const http = axios.create({
  baseURL: baseURL, // api的base_url
  withCredentials: true,
  timeout: 1000 * 60 * 30, // request timeout
});

http.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = function(data) {
  if (!isPlainObject(data)) return data;
  return qs.stringify(data);
};

// 请求前预处理
http.interceptors.request.use(
  (config) => {
    let token = localStorage.getItem('token');
    if (token) config.headers['Authorization'] = token;

    config.data = config.data || {};

    return config;
  },
  (error) => {
    // Do something with request error
    Promise.reject(error);
  }
);

// respone interceptor
http.interceptors.response.use(
  (response) => {
    if (response['status'] === 200) {
      // 请求响应成功
      let data = response['data'];
      return data;
    } else {
      return response;
    }
  },
  (error) => {
    // @1 服务器返回信息，状态码不是以2开始
    if (error.response) {
      switch (error.response.status) {
        case 400:
          // ...
          break;
      }
    }

    // @2 服务器没有返回的信息「请求超时或者中断」
    if (error.code === 'ECONNABORTED') {
      // ...
    }

    // @3 服务器没有返回的信息「断网了」
    if (!navigator.onLine) {
      // ...
    }

    return Promise.reject(error);
  }
);

export default http;
